package edu.cmu.ri.createlab.monarch.examples;

import com.google.protobuf.RpcCallback;
import com.googlecode.protobuf.socketrpc.SocketRpcChannel;
import com.googlecode.protobuf.socketrpc.SocketRpcController;
import edu.cmu.ri.createlab.monarch.MonarchConstants;
import edu.cmu.ri.createlab.monarch.rpc.UserServiceProto;
import org.apache.log4j.Logger;

/**
 * @author Chris Bartley (bartley@cmu.edu)
 */
public class ExampleClient
   {
   private static final Logger LOG = Logger.getLogger(ExampleClient.class);

   public static void main(final String[] args)
      {
      String host = MonarchConstants.DEFAULT_SERVER_HOST;
      if (args.length >= 1)
         {
         host = args[0];
         }

      int port = MonarchConstants.DEFAULT_SERVER_PORT;
      if (args.length >= 2)
         {
         try
            {
            port = Integer.parseInt(args[1]);
            }
         catch (NumberFormatException ignored)
            {
            LOG.error("NumberFormatException while trying to parse [] as an int.  Defaulting to [" + MonarchConstants.DEFAULT_SERVER_PORT + "]");
            port = MonarchConstants.DEFAULT_SERVER_PORT;
            }
         }

      LOG.info("Attempting connection to " + host + ":" + port + "...");

      // Create channel
      final SocketRpcChannel socketRpcChannel = new SocketRpcChannel(host, port);
      final SocketRpcController rpcController = socketRpcChannel.newRpcController();

      // Call service
      final UserServiceProto.UserService myService = UserServiceProto.UserService.newStub(socketRpcChannel);
      final UserServiceProto.NumberRequest request = UserServiceProto.NumberRequest.newBuilder().build();
      myService.getNumber(rpcController, request,
                          new RpcCallback<UserServiceProto.NumberResponse>()
                          {
                          public void run(final UserServiceProto.NumberResponse myResponse)
                             {
                             LOG.info("Received Response: " + myResponse.getNumber());
                             }
                          });

      // Check success
      if (rpcController.failed())
         {
         LOG.info(String.format("Rpc failed %s : %s",
                                rpcController.errorReason(),
                                rpcController.errorText()));
         }
      }

   private ExampleClient()
      {
      // private to prevent instantiation
      }
   }
